/* 
    卡片副页
*/

import { CameraOutlined, CopyOutlined, HeartOutlined, PlayCircleOutlined } from '@ant-design/icons'
import { Button, Card, FloatButton, message } from 'antd'
import ClipboardJS from 'clipboard'
import html2canvas from 'html2canvas'
import MarkdownIt from 'markdown-it'
import React, { useEffect, useRef, useState } from 'react'
import MdEditor from 'react-markdown-editor-lite'
import { useNavigate, useParams } from 'react-router-dom'

import { ApiClient } from '../shared/request'

const mdParser = new MarkdownIt()

const CardDetail = () => {
    let navigate = useNavigate()
    let { id } = useParams()

    const [isSaved, setIsSaved] = useState(true)
    const [editingTitle, setEditingTitle] = useState(false)
    const [title, setTitle] = useState('')
    const [content, setContent] = useState('')
    const contentRef = useRef(null)

    useEffect(() => {
        ApiClient.card({}, id).then((resp) => {
            const { _, title, content } = resp
            setTitle(title)
            setContent(content)
            setIsSaved(true)
        })
    }, [id])

    useEffect(() => {
        const clipboard = new ClipboardJS('#copyButton', {
            text: () => content,
        })

        return () => {
            clipboard.destroy()
        }
    }, [content])

    const handleTitleChange = (newTitle) => {
        setTitle(newTitle)
        setIsSaved(false)
    }

    const handleContentChange = ({ text }) => {
        setContent(text)
        setIsSaved(false)
    }

    const autoSave = () => {
        const opts = { title: title, content: content }
        ApiClient.update(opts, id)
            .then(resp => {
                console.log("Card manually saved successfully:", resp)
                setIsSaved(true)
                message.success('保存成功')
            })
            .catch(error => {
                console.error("Error manually saving card:", error)
                message.error('保存失败')
            })
    }

    const handleBlur = () => {
        setTimeout(autoSave(), 3000)
    }

    const extractPythonCodeBlocks = (markdownText) => {
        const codeBlockRegex = /```python([\s\S]*?)```/g
        const matches = []
        let match

        while ((match = codeBlockRegex.exec(markdownText)) !== null) {
            const codeContent = match[1].trim()
            matches.push({ language: 'python', content: codeContent })
        }

        return matches
    }

    const sendCodeBlocksToRemoteAPI = (codeBlocks) => {
        interpreter.python(codeBlocks)
            .then(resp => {
                console.log('远程执行成功:', resp[0])
                message.success({
                    content: resp[0],
                    duration: 5,
                })
            })
            .catch(error => {
                console.error('远程执行失败:', error)
                message.error('远程执行失败')
            })
    }


    const handleFloatButtonClick = (key) => {
        switch (key) {
            case 'copy':
                // 复制操作
                message.success('复制操作')
                break
            case 'run':
                // 运行操作
                const codeBlocks = extractPythonCodeBlocks(content)

                if (codeBlocks.length > 0) {
                    message.success('检测到代码，正在提交远程执行！')
                    sendCodeBlocksToRemoteAPI(codeBlocks)
                } else {
                    message.warning('未检测到Python代码块')
                }
                break
            case 'screenshot':
                // 全屏截图操作
                html2canvas(document.body).then(canvas => {
                    const timestamp = Date.now()
                    const screenshotDataUrl = canvas.toDataURL('image/png')
                    const downloadLink = document.createElement('a')
                    downloadLink.href = screenshotDataUrl
                    downloadLink.download = `${timestamp}.png`
                    downloadLink.click()
                    message.success('全屏截图成功')
                }).catch(error => {
                    console.error('截图失败:', error)
                    message.error('截图失败')
                })
                break
            default:
                break
        }
    }

    const handleKeyDown = (e) => {
        // Check if Ctrl+S is pressed
        if (e.ctrlKey && e.key === 's') {
            e.preventDefault() // Prevent browser's default save behavior
            autoSave()
        }
    }

    return (
        <div onKeyDown={handleKeyDown} tabIndex={0}>
            <Button type="dashed" onClick={() => navigate(-1)}>
                返回
                {isSaved ? <span style={{ marginLeft: '8px', color: 'green' }}>&#8226;</span> :
                    <span style={{ marginLeft: '8px', color: 'red' }}>&#8226;</span>}
            </Button>

            <FloatButton.Group
                trigger="hover"
                type="primary"
                style={{
                    right: 100,
                    position: 'fixed',
                    bottom: 50,
                }}
                icon={<HeartOutlined />}
            >
                <FloatButton
                    icon={<PlayCircleOutlined />}
                    tooltip={
                        <div>
                            运行代码(Any)
                            <br />
                            rpc支持
                        </div>
                    }
                    onClick={() => handleFloatButtonClick('run')}
                />
                <FloatButton
                    id="copyButton"
                    icon={<CopyOutlined />}
                    tooltip={<div>复制全文</div>}
                    onClick={() => handleFloatButtonClick('copy')}
                />
                <FloatButton
                    icon={<CameraOutlined />}
                    tooltip={<div>截屏</div>}
                    onClick={() => handleFloatButtonClick('screenshot')}
                />
            </FloatButton.Group>

            <Card title={
                editingTitle ?
                    <input
                        type="text"
                        style={{
                            border: 'none',
                            width: '100%',
                            textAlign: 'center',
                            background: 'transparent',
                            resize: 'none',
                        }}
                        value={title}
                        onChange={(e) => handleTitleChange(e.target.value)}
                        onBlur={handleBlur}
                        autoFocus
                    /> :
                    <div
                        style={{
                            width: '100%',
                            textAlign: 'center',
                            background: 'transparent',
                            cursor: 'pointer',
                        }}
                        onClick={() => setEditingTitle(true)}
                    >
                        {title ? title : '点击编辑标题'}
                    </div>
            }>
                <MdEditor
                    value={content}
                    style={{ height: '600px' }}
                    renderHTML={(text) => mdParser.render(text)}
                    onChange={handleContentChange}
                    onBlur={handleBlur}
                    ref={contentRef}
                />

            </Card>
        </div>
    )
}

export default CardDetail
